import 'dart:async';

import 'package:chathouse/model/client_order.dart';
import 'package:chathouse/pages/client/order/comment_order_page.dart';
import 'package:chathouse/pages/route_manager/root_route_manager.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:chathouse/util/log.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../chat/chat_page.dart';
import '../../public/empty_widget.dart';
import 'dart:math';

import '../client/order/comment_detail.dart';

///专家项目列表
class ExpertOrderList extends StatefulWidget {
  var type;

  ExpertOrderList(this.type, {Key? key}) : super(key: key);

  @override
  State<ExpertOrderList> createState() => _ExpertOrderListState();
}

class _ExpertOrderListState extends State<ExpertOrderList>
    with NavigationHelper, AutomaticKeepAliveClientMixin {
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false); // 刷新控件控制
  ClientOrder? clientOrder;
  StreamSubscription? refreshSubscription;

  int pageNum = 1;
  List<Rows>? rows = [];

  loadMore() {
    if ((rows?.length ?? 0) >= (clientOrder?.total ?? 0)) {
      _refreshController.loadComplete();
      return;
    }
    pageNum += 1;
    requestData();
  }

  clearLoad() {
    pageNum = 1;
    rows?.clear();
    if (widget.type == 2) {
      expertComUser();
    } else {
      requestData();
    }
  }

  @override
  void initState() {
    super.initState();
    if (widget.type == 2) {
      expertComUser();
    } else {
      requestData();
    }
  }

  void requestData() {
    Obj.showLoading();
    final params = {"acceptFlag": widget.type, "pageNum": pageNum};
    Apis.expertOrderList(params).then((value) {
      Obj.dismissLoading();
      _refreshController.refreshCompleted();
      _refreshController.loadComplete();
      var json = value?.data;
      if (json == null) {
        return;
      }
      clientOrder = ClientOrder.fromJson(json);
      rows?.addAll(clientOrder?.rows ?? []);
      setState(() {});
    }).catchError((error) {
      Obj.dismissLoading();
      _refreshController.refreshCompleted();
      _refreshController.loadComplete();
    });
  }

  void expertComUser() {
    Obj.showLoading();
    // final params = {"acceptFlag": widget.type, "pageNum": pageNum};
    Apis.expertComUser({}).then((value) {
      Obj.dismissLoading();
      _refreshController.refreshCompleted();
      var json = value?.data;
      if (json == null) {
        return;
      }
      clientOrder = ClientOrder.fromJson(json);
      rows?.addAll(clientOrder?.rows ?? []);
      setState(() {});
    }).catchError((error) {
      Obj.dismissLoading();
      _refreshController.refreshCompleted();
      // _refreshController.loadComplete();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: null,
      body: SmartRefresher(
        enablePullDown: true,
        enablePullUp: false,
        controller: _refreshController,
        onRefresh: clearLoad,
        onLoading: () {
          loadMore();
        },
        child: rows?.length == 0
            ? const EmptyWidget(
                emptyText: '暂無项目數據',
              )
            : _getListView(),
      ),
    );
  }

  Widget _getEmptyWidget() {
    return Center(
        child: Text("沒有資料",
            style: getTextStyle(25.sp,
                color: MyColors.gary_139139139, fontType: FontType.BOLD)));
  }

  Widget _getListView() {
    if (clientOrder == null) {
      return _getEmptyWidget();
    }
    if (rows?.isEmpty ?? true) {
      return _getEmptyWidget();
    }

    return ListView.separated(
      shrinkWrap: true,
      separatorBuilder: (BuildContext context, int index) {
        return Container(height: 0.2.w, color: Styles.c_ccc);
      },
      padding: EdgeInsets.fromLTRB(12.w, 0, 12.w, 12.w),
      itemCount: rows!.length + 1,
      itemBuilder: (context, index) {
        if (index == rows!.length) {
          return Container(height: 0.2.w, color: MyColors.gary_112112112);
        }
        return buildItem(index);
      },
    );
  }

  ///构建 item
  Widget buildItem(index) {
    Rows? item = rows?[index];
    Color color = Styles.c_666;

    double number = item?.serviceEvaluation ?? 0;
    List stars = [];
    if (widget.type == 2) {
      for (int i = 0; i < number.ceil(); i++) {
        stars.add(i);
      }
    }
    if (item?.acceptFlag == "0" || item?.acceptFlag == "2") {
      color = Styles.c_666;
    }
    if (item?.acceptFlag == "1") {
      color = Styles.mainColor;
    }
    return Container(
        padding: EdgeInsets.only(top: 20.w, bottom: 20.w),
        // color:Colors.red,
        child: Column(children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Container(
                  margin: EdgeInsets.only(left: 16.w),
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(item?.serviceName ?? "",
                            style: getTextStyle(28.sp,
                                color: Styles.c_191919,
                                fontType: FontType.BOLD)),
                        SizedBox(
                          height: 4.w,
                        ),
                        Text(item?.membersName ?? "",
                            style: getTextStyle(22.sp,
                                color: Styles.c_666, fontType: FontType.BOLD)),
                      ]),
                ),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Container(
                    height: 6.w,
                  ),
                  Text(item?.createTime ?? "",
                      style: getTextStyle(14.sp,
                          color: Styles.c_666, fontType: FontType.MID)),
                  Container(
                    height: 6.w,
                  ),
                  widget.type != 2
                      ? Text(item?.acceptFlagStr() ?? "",
                          style: getTextStyle(16.sp,
                              color: color, fontType: FontType.BOLD))
                      : Container(
                          width: 100,
                          height: 20,
                          margin: EdgeInsets.only(top: 4.w),
                          // color: Colors.redAccent,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: List.generate(stars.length ?? 0, (index) {
                              return const Icon(Icons.star,
                                  size: 18, color: Colors.redAccent);
                            }),
                          ),
                        ),
                ],
              )
            ],
          ),
        ])).setOnClickListener(() {
      if (widget.type == 2) {
        double number = item?.serviceEvaluation ?? 0;
        var intNumber = number.toInt();
        final map = {
          "serviceName": item?.serviceName,
          "membersName": item?.membersName,
          "serviceEvaluation": intNumber,
          "comUser": item?.comUser
        };
        Get.to(CommentDetailPage(map));
      } else {
        final map = {
          "reviceuserId": item?.membersNo,
          "projectNo": item?.projectNo,
          "projectId": item?.projectId,
          "memberImage": item?.memberImage,
          "membersName": item?.membersName,
          "evaluate": item?.evaluate
        };
        Get.to(ChatPage(map));
      }
    }, isInkWell: true);
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
